<!-- src/components/MenuItem.vue -->
<template>
  <!-- 如果有可见的子菜单（过滤后） -->
  <el-sub-menu v-if="hasVisibleChildren" :index="rootPath">
    <template #title>{{ item.meta?.title || item.name }}</template>
    <menu-item
        v-for="child in visibleChildren"
        :key="child.path"
        :item="child"
        :base-path="rootPath"
    />
  </el-sub-menu>

  <!-- 如果是叶子节点 -->
  <el-menu-item v-else :index="rootPath">
    {{ item.meta?.title || item.name }}
  </el-menu-item>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  basePath: {
    type: String,
    default: ''
  }
});

// 判断是否为外链
const isExternal = (path) => /^(https?:|mailto:|tel:)/.test(path);

// 计算当前项的“根路径”（绝对路径）
const rootPath = computed(() => {
  if (isExternal(props.item.path)) return props.item.path;
  if (props.item.path.startsWith('/')) return props.item.path;
  if (props.basePath && props.basePath !== '/') {
    return `${props.basePath}/${props.item.path}`.replace(/\/+/g, '/');
  }
  return `/${props.item.path}`.replace(/\/+/g, '/');
});

// 获取可见的子路由
const visibleChildren = computed(() => {
  const children = props.item.children || [];
  return children.filter(child => !child.meta?.hidden);
});

// 是否有可见子菜单
const hasVisibleChildren = computed(() => visibleChildren.value.length > 0);
</script>
